# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
import datetime
import logging
from django.contrib.admin.views.decorators import staff_member_required
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.forms.models import save_instance
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotAllowed, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.utils.translation import ugettext as _

from forms import UploadForm
from models import Upload
from forms import UploadFileForm
from django.core.context_processors import csrf
from models import ReportSum, ReportGraph
from django.core import serializers 

RECORDS_PER_PAGE=2
VISIBLE_PAGES=3

def index(request):
    t = loader.get_template('index.html')
    c = RequestContext({
        "upload": "aaa"         
    })
    return HttpResponse(t.render(c))

from UsageSummary import settings
def report(request):
    print settings.MEDIA_ROOT
    return render_to_response('DataToMultiSelect2.htm')


def confirm_delete(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    
    upload = get_object_or_404(Upload, id=request.POST.get('id', None))
    data = {
        'upload': upload
    }
    return render_to_response('confirm_delete.html', data, RequestContext(request))


def delete(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    
    if request.POST.get('delete', False):
        upload = get_object_or_404(Upload, id=request.POST.get('id', None))
        upload.delete()
        #request.user.message_set.create(message=_('The file has been deleted.'))

    return HttpResponseRedirect(reverse('uploads'))

def list(request):
    data = {
        'form': UploadForm(),
        'uploads': Upload.objects.all()
    }
    return render_to_response('list.html', data, RequestContext(request))

from ReadFile import handle_uploaded_file


def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        #form2 = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])

            logging.info("Upload form is valid: %s" % form)
            upload = Upload()
            upload.uploaded_by = request.user
            upload.timestamp = datetime.datetime.now()
            
            save_instance(form, upload)
            logging.info("Saved upload: %s" % upload)
            #request.user.message_set.create(message=_('Your file has been received.'))
        else:
            logging.error("invalid form: %s" % form)
            logging.error("form errors: %s" % form.errors)

    return HttpResponseRedirect(reverse('uploads'))



def upload_progress(request):
    """
    Return JSON object with information about the progress of an upload.
    """
    if 'HTTP_X_PROGRESS_ID' in request.META:
        progress_id = request.META['HTTP_X_PROGRESS_ID']
        from django.utils import simplejson
        cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
        data = cache.get(cache_key)
        json = simplejson.dumps(data)
        return HttpResponse(json)
    else:
        logging.error("Received progress report request without X-Progress-ID header. request.META: %s" % request.META)
        return HttpResponseBadRequest('Server Error: You must provide X-Progress-ID header or query param.')


#JQGRID
def jqfilter(op,field):
    """We need to make the conversion from the search parameters that
    jqgrid sends and the sql ones.
    I you send a non existing codintion it would apply the equal one"""

    jqgrid = {'bw': ("%s like %%s", "%s%%"  ),
              'eq': ("%s = %%s",    "%s"    ),
              'gt': ("%s > %%s",    "%s"    ),
              'ge': ("%s >= %%s",   "%s"    ),
              'ne': ("%s <> %%s",   "%s"    ),
              'lt': ("%s < %%s",    "%s"    ),
              'le': ("%s <= %%s",   "%s"    ),
              'ew': ("%s like %%s", "%%%s"  ),
              'cn': ("%s like %%s", "%%%s%%")
              }
    try:
        condition, template = jqgrid[op]
    except:
        condition, template = jqgrid['eq']
    return condition % field, template

def ajax_dades(request):
    """Ajax needed by  jqgrid. This is not generic nor the best code you can have 
    but for teaching purposes I prefer to sacrifice style.   
    
    This code takes a python object, Person in our case and deals with pagination,
    and filters as is sent by jqGrid.
    
    """

    orden = "id" if (request.GET.get('sidx')=="" or None) else request.GET.get('sidx') 
    sort_order = "" if request.GET.get('sord') == "asc" else "-"
    orden = str(sort_order) + str(orden)
    pagina = int(request.GET.get('page')) if request.GET.get('page') != 'page' else 1 
    files = int(request.GET.get('rows'))  # files = rows in catalan :)
    
    # Here goes the model.--
    #insertToReportSum()
    dades = ReportSum.objects
    # ----------------------
    
    # We compute what we are going to present in the grid

    if request.GET.get('_search')=='true':
        # We're on searching mode
        searchField = request.GET.get('searchField')
        searchOp = request.GET.get('searchOper')
        field, template = jqfilter(searchOp, searchField)
        fields = [ field ]
        values = [ template  % request.GET.get('searchString')]
        try:
            total = dades.all().extra(where=fields, params = values).count()
            rta = dades.all().extra(where=fields, params = values)
        except Exception, e:
            print e
            data = '{"total":%(pages)s, "page":%(page)s, "records":%(total)s, "rows":%(rta)s }'\
                % {'pages':0, 'page':0, 'total':0, 'rta':None}
            return HttpResponse(data, mimetype="application/json")
    else:
        # Normal mode, so no filters applied
        rta = dades.all()
        total = dades.all().count() 
    
    # Page calculation
    reste = 1 if total % files >0 else 0
    pages = total / files  + reste
    if pagina > pages:
        pagina = 1

    # Get just the data we needo for our page
    rta = rta.order_by(orden)[(pagina-1)*files:pagina*files]

    #just for debug purposes
    #if settings.DEBUG:
        #print 
        #print "QUERY ==="
        #print dades.all()
        #print "==========================================="
        #print
    
    # We build the json that jqgrid likes best :)
    rows = serializers.serialize("json",rta)
    #print rows[0]
    dades = '{"total":%(pages)s, "page":%(page)s, "records":%(total)s, "rows":%(rta)s }' % {'pages':pages, 'page':pagina, 'total':total, 'rta':rows}
    return HttpResponse(dades, mimetype='application/json')
 
def ajax_jqplot(request):
    # Here goes the model.--
    #insertToReportSum()
    dades = ReportSum.objects
    # ----------------------
    rta = dades.all()
    
    #print "QUERY ==="
    #for a in rta:
        #print a.Attempts
        #print "==========================================="
        #print
    
    # We build the json that jqgrid likes best :)
    #rows = serializers.serialize("json",dades)
    #print rows[0]['Country']
    #dades = '{"total":%(pages)s, "page":%(page)s, "records":%(total)s, "rows":%(rta)s }' % {'pages':pages, 'page':pagina, 'total':total, 'rta':rows}
    #return HttpResponse(rows, mimetype='application/json')
    #return dades
    result = []
    for record in rta:
        result.append({"id":record.Attempts, "name":record.Completed})
    for a in result:
        print a
 
 
def data(request):
    dades = ReportSum.objects.all()
    arr = []
    for a in dades:
        arr.append(a.Attempts)
        print a.Attemps
    return arr

def xhr_test(request):
    
    #rep = ReportSum.objects.values('Country').annotate(Attempts=Sum('Attempts'), Completed=Sum('Completed'), ASR=Sum('ASR'), ACD=Sum('ACD'), RawDur=Sum('RawDur'))
    rep = ReportGraph.objects.all()
    #rep.values('Country').annotate(dsum=Sum('Attempts'))

    if request.is_ajax():
        mimetype = 'application/javascript'
        data = serializers.serialize('json', rep)
        #print data
        return HttpResponse(data,mimetype)
    # If you want to prevent non XHR calls
    else:
        return HttpResponse(status=400)
     #jsonObj = [{ "pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ['Jan 2009', 'Feb 2009', 'Mar 2009', 'Apr 2009', 'May 2009', 'June 2009', 'Jul 2009'] }]
     #return HttpResponse(jsonObj,'application/javascript')
